package com.example.reagent_management.ui.message

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.filter
import com.example.reagent_management.ui.message.pojo.Message
import com.example.reagent_management.ui.message.pojo.MessageRepository
import com.kunminx.architecture.ui.callback.UnPeekLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MessageViewModel @Inject constructor(private val messageRepository: MessageRepository) :
    ViewModel() {

    val allMessage = UnPeekLiveData<PagingData<Message>>()
    val changeState = UnPeekLiveData<Int>()

   fun getAllMessage(filter:String): Job {
        return viewModelScope.launch(Dispatchers.IO) {
            //优化？ 不应频繁取消主协程工作，子协程一次性工作即可
            val job = launch {
                messageRepository.getALlMessage()
                    .flowOn(Dispatchers.Default)
                    .cachedIn(this)
                    .collectLatest { data ->
                        delay(60)
                        if (filter.isNotEmpty()) {
                            val filterData = data.filter {
                                it.messages.contains(filter)
                            }
                            allMessage.postValue(filterData)
                        } else {
                            allMessage.postValue(data)
                        }
                    }
            }
            job.invokeOnCompletion {  }
            job.join()
        }
    }

    fun deleteALlMessage(){
        viewModelScope.launch(Dispatchers.IO) {
            messageRepository.deleteALL()
        }
    }
}